package com.idak.spring.jdbc.dao.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Repository;

import com.idak.spring.jdbc.bean.User;
import com.idak.spring.jdbc.dao.UserDao;
import com.idak.spring.jdbc.util.Constants;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	private SimpleJdbcCall storedFunction;
	private SimpleJdbcCall storedProcedur;
	
	public User getUserByLogin(String login) {
		
		Object[] params = new Object[]{login};
		BeanPropertyRowMapper<User> mapper = new BeanPropertyRowMapper<User>(User.class);
		
		User user = jdbcTemplate.queryForObject(Constants.Queries.GET_USER_BY_LOGIN, params, mapper);
		throw new NullPointerException();
		//return user;
	}

	public List<User> getAllUsers() {
		BeanPropertyRowMapper<User> mapper = new BeanPropertyRowMapper<User>(User.class);
		List<User> users = jdbcTemplate.query(Constants.Queries.GET_ALL_USERS, mapper);
		
		return users;
	}

	public boolean isEnabledLogin(String login) {
		this.storedFunction = new SimpleJdbcCall(jdbcTemplate).withFunctionName("is_enabled_user");
		SqlParameterSource in = new MapSqlParameterSource().addValue("s", login);
		int result = storedFunction.executeFunction(Integer.class,in);
		return result == 1;
	}

	public Map<String, Object> callStoredProcedure(String dt) {
		this.storedProcedur = new SimpleJdbcCall(jdbcTemplate).withProcedureName("findAppointments");
		Map<String, String> inputs = new LinkedHashMap<String, String>();
		inputs.put("dt", dt);
		
		Map<String, Object> result = storedProcedur.execute(inputs);

		return result;
	}
}
